package com.stylefeng.guns.modular.system.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.KeyUtil;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.dao.CollectBasicInformationMapper;
import com.stylefeng.guns.modular.system.model.CarryBasicInformation;
import com.stylefeng.guns.modular.system.model.CarryContractInformation;
import com.stylefeng.guns.modular.system.model.CollectBasicInformation;
import com.stylefeng.guns.modular.system.model.CollectCarryInformation;
import com.stylefeng.guns.modular.system.model.Collectmoney;
import com.stylefeng.guns.modular.system.model.InitId;
import com.stylefeng.guns.modular.system.model.ModelCheck;
import com.stylefeng.guns.modular.system.model.ModelCollection;
import com.stylefeng.guns.modular.system.model.ModelCollectionAdd;
import com.stylefeng.guns.modular.system.model.ReceiveBasicInformation;
import com.stylefeng.guns.modular.system.service.ICarryBasicInformationService;
import com.stylefeng.guns.modular.system.service.ICarryContractInformationService;
import com.stylefeng.guns.modular.system.service.ICollectBasicInformationService;
import com.stylefeng.guns.modular.system.service.ICollectCarryInformationService;
import com.stylefeng.guns.modular.system.service.ICollectmoneyService;
import com.stylefeng.guns.modular.system.service.IInitIdService;
import com.stylefeng.guns.modular.system.service.IReceiveBasicInformationService;

/**
 * 收款登记控制器
 *
 * @author fengshuonan
 * @Date 2018-05-02 22:56:57
 */
@Controller
@RequestMapping("/collectBasicInformation")
public class CollectBasicInformationController extends BaseController {

    private String PREFIX = "/system/collectBasicInformation/";

    @Autowired
    private ICollectBasicInformationService collectBasicInformationService;
    @Autowired
    private CollectBasicInformationMapper collectBasicInformationMapper;
    @Autowired
    private IReceiveBasicInformationService basicInformationService;
    @Autowired
    private ICarryContractInformationService carryContractInformationService;
    @Autowired
    private ICarryBasicInformationService carryBasicInformationService;
    @Autowired
    private ICollectmoneyService collectmoneyService;
    @Autowired
    private ICollectCarryInformationService collectCarryInformationService;
    
  //合同号生成
    @Autowired
    private IInitIdService initIdService;
    
    public  String init3ID(int id){
		String number = id+"";
		int size = 3-number.length();
		StringBuffer str = new StringBuffer();
		for(int i=0;i<size;i++){
			str.append("0");
		}
		str.append(number);
		return  str.toString();
	}
    
    private String getCollectNumber(){
    	
    	Date now = new Date();
		DateFormat format = new SimpleDateFormat("yyyyMMdd");
		String nowDate = format.format(now);
		InitId initId  = initIdService.selectList(null).get(0);
		String dbNumber = initId.getCollectId();
		String dbID = dbNumber.substring(8);
		String dbDate = dbNumber.substring(0, 8);
		if(nowDate.equals(dbDate)){
			int ID = Integer.parseInt(dbID);
			ID++;
			return nowDate+init3ID(ID);
		}else{
			return nowDate+"001";
		}
		
    }

    /**
     * 跳转到收款登记首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "collectBasicInformation.html";
    }
    /**
     * 审核跳转
     */
    @RequestMapping("check")
    public String index02() {
    	return "/check/collectBasicInformation/" + "collectBasicInformation.html";
    }
    
    /**
     * 查询跳转
     */
    @RequestMapping("boss")
    public String index03() {
    	return "/query/collectBasicInformation/" + "collectBasicInformation.html";
    }

    /**
     * 跳转到添加收款登记
     */
    @RequestMapping("/collectBasicInformation_add")
    public String collectBasicInformationAdd(Model model) {
    	String collectID= getCollectNumber();
    	ShiroUser shiroUser = ShiroKit.getUser();
    	String username=shiroUser.getName();
    	model.addAttribute("username", username);
    	model.addAttribute("collectID", collectID);
        return PREFIX + "collectBasicInformation_add.html";
    }
    
    /**
     * 通过合同号模糊查询合同信息到前台显示，进行装车操作
     */
    @RequestMapping(value="/querybycontractnumber")
    @ResponseBody
    public Object queryByContractNumber(@RequestParam String searchContract){
    	List<ReceiveBasicInformation> receiveBasicInformations = basicInformationService.getCollectBasic(searchContract);
    	return receiveBasicInformations;
    }
    /**
     * 通过合同号查询出装车号到前台，供用户选择
     * @param contractNumber
     * @return
     */
    @RequestMapping(value="/getcarrynumber")
    @ResponseBody
    public Object queryCarryNumber(@RequestParam String contractNumber){
    	EntityWrapper<CarryContractInformation> entityWrapper = new EntityWrapper<>();
    	Wrapper<CarryContractInformation> wrapper = entityWrapper.eq("carry_contract_number", contractNumber);
    	List<CarryContractInformation> lists = carryContractInformationService.selectList(wrapper);
    	List<CarryContractInformation> carryContractInformations = new ArrayList<>();
    	for(CarryContractInformation carryContractInformation:lists){
    		if(!ToolUtil.isEmpty(carryContractInformations)){
    			boolean notEqual = true;
    			for(CarryContractInformation carryContract:carryContractInformations){
    				if(carryContractInformation.getForeignKeyCarryId().equals(carryContract.getForeignKeyCarryId())){
    					notEqual = false;
    				}
    			}
    			if(notEqual){
    				carryContractInformations.add(carryContractInformation);
    			}
    		}else{
    			carryContractInformations.add(carryContractInformation);
    		}
    	}
    	return carryContractInformations;
    }
    /**
     * 通过用户自主选择的合同号与装车号进行精确的合同筛选
     * @param carryNumber
     * @param contractNumber
     * @return
     */
    @RequestMapping(value="/getcarry")
    @ResponseBody
    public Object queryCarry(String carryNumber,String contractNumber){
    	//获取装车登记基本信息
    	EntityWrapper<CarryBasicInformation> entityWrapper = new EntityWrapper<>();
    	Wrapper<CarryBasicInformation> wrapper = entityWrapper.eq("carry_id", carryNumber);
    	CarryBasicInformation carryBasicInformation = carryBasicInformationService.selectList(wrapper).get(0);
    	//获取装车登记详细信息
    	EntityWrapper<CarryContractInformation> entityWrapper1 = new EntityWrapper<>();
    	Wrapper<CarryContractInformation> wrapper1 = entityWrapper1.eq("carry_contract_number", contractNumber).eq("foreign_key_carry_id", carryNumber);
    	List<CarryContractInformation> carryContractInformations = carryContractInformationService.selectList(wrapper1);
    	//获取收款表
    	EntityWrapper<Collectmoney> entityWrapper2 = new EntityWrapper<>();
    	Wrapper<Collectmoney> wrapper2 = entityWrapper2.eq("contract_number", contractNumber);
    	Collectmoney collectmoney = collectmoneyService.selectList(wrapper2).get(0);
    	
    	ModelCollectionAdd modelCollection = new ModelCollectionAdd();
    	modelCollection.setCarryBasicInformation(carryBasicInformation);
    	modelCollection.setCarryContractInformation(carryContractInformations);
    	modelCollection.setCollectMoney(collectmoney);
    	return modelCollection;
    }
    
    
    /**
     * 制单员跳转到修改收款登记
     */
    @RequestMapping("/collectBasicInformation_update/{collectBasicInformationId}")
    public String collectBasicInformationUpdate(@PathVariable Integer collectBasicInformationId, Model model) {
    	ModelCollection modelCollection = new ModelCollection();
    	CollectBasicInformation collectBasicInformation = collectBasicInformationService.selectById(collectBasicInformationId);
    	
    	String collectId = collectBasicInformation.getCollectId();
    	EntityWrapper<CollectCarryInformation> entityWrapper1 = new EntityWrapper<>();
    	Wrapper<CollectCarryInformation> wrapper1 = entityWrapper1.eq("collect_collection_id", collectId);
    	List<CollectCarryInformation> collectCarryInformations = collectCarryInformationService.selectList(wrapper1);
    	
    	modelCollection.setCollectBasicInformation(collectBasicInformation);
    	modelCollection.setCollectCarryInformations(collectCarryInformations);
    	model.addAttribute("item", modelCollection);
        return PREFIX + "collectBasicInformation_edit.html";
    }

    /**
     * 获取收款登记列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list() {
    	 Page<CollectBasicInformation> page = new PageFactory<CollectBasicInformation>().defaultPage();  
         EntityWrapper<CollectBasicInformation> entityWrapper = new EntityWrapper<>();  
         ShiroUser shiroUser = ShiroKit.getUser();
     	 String username=shiroUser.getName();
        //倒序排序
     	List<String> str= new ArrayList<>();
 		str.add("id");
          entityWrapper.eq("collect_state", KeyUtil.CHECK_STATE_UNCHECKED).or().eq("collect_state", KeyUtil.CHECK_STATE_FAIL_UNCHECKED);  
          Wrapper<CollectBasicInformation> wrapper =entityWrapper.andNew().eq("collect_trade_person", username).orderDesc(str);
         page.setRecords(collectBasicInformationMapper.selectPage(page,wrapper));  
         return super.packForBT(page);   
    }

    /**
     * 制单员新增收款登记
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@RequestBody ModelCollection modelCollection) {
    	CollectBasicInformation collectBasicInformation = modelCollection.getCollectBasicInformation();
    	String collectId = collectBasicInformation.getCollectId();
    	List<CollectCarryInformation> collectCarryInformations = modelCollection.getCollectCarryInformations();
    	for(CollectCarryInformation collectCarryInformation:collectCarryInformations){
    		collectCarryInformation.setCollectCollectionId(collectId);
    		collectCarryInformationService.insert(collectCarryInformation);
    	}
    	collectBasicInformation.setCollectState(KeyUtil.CHECK_STATE_UNCHECKED);
    	collectBasicInformationService.insert(collectBasicInformation);
    	
    	 InitId initIdDB  = initIdService.selectList(null).get(0);
 		long dbNumber = Long.parseLong(initIdDB.getCollectId().trim());
 		long number = Long.parseLong(collectBasicInformation.getCollectId().trim());
 		if(number-dbNumber>0){
 			//增加成功后，使用掉一个号码
 			InitId initId = new InitId();
 			initId.setId(1);
 			initId.setCollectId(collectBasicInformation.getCollectId());
 			initIdService.updateById(initId);
 		}
    	 return "SUCCESS";
    }

    /**
     * 删除收款登记
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer collectBasicInformationId) {
    	CollectBasicInformation collectBasicInformation = collectBasicInformationService.selectById(collectBasicInformationId);
    	String collectId = collectBasicInformation.getCollectId();
    	
    	//删除收款等级详情表
    	EntityWrapper<CollectCarryInformation> entityWrapper1 = new EntityWrapper<>();
    	Wrapper<CollectCarryInformation> wrapper1 = entityWrapper1.eq("collect_collection_id", collectId);
    	collectCarryInformationService.delete(wrapper1);
    	
    	//删除收款登记基本表
        collectBasicInformationService.deleteById(collectBasicInformationId);
        return SUCCESS_TIP;
    }

    /**
     * 修改收款登记
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(@RequestBody ModelCollection modelCollection) {
    	//如果收款基本表的状态为已通过的话，则不能进行修改
    	CollectBasicInformation collectBasicInformation = modelCollection.getCollectBasicInformation();
    	if(collectBasicInformation.getCollectState().equals(KeyUtil.CHECK_STATE_SUCCESS_CHECKED)){
    		return "fail";
    	}
    	List<CollectCarryInformation> collectCarryInformations = modelCollection.getCollectCarryInformations();
    	for(CollectCarryInformation collectCarryInformation:collectCarryInformations){
    		collectCarryInformationService.updateById(collectCarryInformation);
    	}
    	collectBasicInformation.setCollectState(KeyUtil.CHECK_STATE_UNCHECKED);
        collectBasicInformationService.updateById(collectBasicInformation);
        return "SUCCESS";
    }

    
    /**
     * 获取装车登记,此用于审核员审核的“未审核”的表数据
     */
    @RequestMapping(value = "/listcheck")
    @ResponseBody
    public Object listCheck(){
    	 Page<CollectBasicInformation> page = new PageFactory<CollectBasicInformation>().defaultPage();  
         EntityWrapper<CollectBasicInformation> entityWrapper = new EntityWrapper<>();  
        //倒序排序
     	List<String> str= new ArrayList<>();
 		str.add("id");
          entityWrapper.eq("collect_state", KeyUtil.CHECK_STATE_UNCHECKED);  
          Wrapper<CollectBasicInformation> wrapper =entityWrapper.orderDesc(str);
         page.setRecords(collectBasicInformationMapper.selectPage(page,wrapper));  
         return super.packForBT(page);   
    }
    
    /**
     * 打开审核员审核的详情页面
     */
    @RequestMapping("/collectBasicInformation_updatecheck/{collectBasicInformationId}")
    public String collectBasicInformationUpdateQuery(@PathVariable Integer collectBasicInformationId, Model model) {
    	
    	ModelCollection modelCollection = new ModelCollection();
    	CollectBasicInformation collectBasicInformation = collectBasicInformationService.selectById(collectBasicInformationId);
    	
    	String collectId = collectBasicInformation.getCollectId();
    	EntityWrapper<CollectCarryInformation> entityWrapper1 = new EntityWrapper<>();
    	Wrapper<CollectCarryInformation> wrapper1 = entityWrapper1.eq("collect_collection_id", collectId);
    	List<CollectCarryInformation> collectCarryInformations = collectCarryInformationService.selectList(wrapper1);
    	
    	modelCollection.setCollectBasicInformation(collectBasicInformation);
    	modelCollection.setCollectCarryInformations(collectCarryInformations);
    	
    	//获取审核员信息
    	ShiroUser shiroUser = ShiroKit.getUser();
    	String username=shiroUser.getName();
    	model.addAttribute("item", modelCollection);
    	 model.addAttribute("username",username);
        LogObjectHolder.me().set(modelCollection);
        return "/check/collectBasicInformation/" + "collectBasicInformation_edit.html";
    }
    
    
    /**
     * 审核员判定是否审核通过
     */
    @RequestMapping(value = "/updatecheck")
    @ResponseBody
    public Object updateCheck(@RequestBody ModelCheck modelCheck) {
    	int id = modelCheck.getId();
    	String type = modelCheck.getType();
    	
    	CollectBasicInformation  collectBasicInformation = collectBasicInformationService.selectById(id);
    	//判断该收款登记是否还是已审核状态
    	if(!collectBasicInformation.getCollectState().equals(KeyUtil.CHECK_STATE_UNCHECKED)){
    		return "FAIL";
    	}
    	
    	if(type.equals("yes")){
    		//获取审核员信息
        	ShiroUser shiroUser = ShiroKit.getUser();
        	String username=shiroUser.getName();
        	collectBasicInformation.setCollectCheck(username);
        	//将该登记置为已审核
        	collectBasicInformation.setCollectState(KeyUtil.CHECK_STATE_SUCCESS_CHECKED);
        	collectBasicInformationService.updateById(collectBasicInformation);
        	//减掉收款余额表中数据
        	Double fee = collectBasicInformation.getCollectThisMoney();
        		//根据收款信息找到对应的合同
        	EntityWrapper<CollectCarryInformation> entityWrapper = new EntityWrapper<>();
        	Wrapper<CollectCarryInformation> wrapper = entityWrapper.eq("collect_collection_id", collectBasicInformation.getCollectId());
        	CollectCarryInformation collectCarryInformation = collectCarryInformationService.selectList(wrapper).get(0);
        	String contractNumber = collectCarryInformation.getCollectContractNumber();
        		//获取收款表
        	EntityWrapper<Collectmoney> entityWrapper2 = new EntityWrapper<>();
        	Wrapper<Collectmoney> wrapper2 = entityWrapper2.eq("contract_number", contractNumber);
        	Collectmoney collectmoney = collectmoneyService.selectList(wrapper2).get(0);
        	Double feeBefore = collectmoney.getUncollectMoney()-fee;
        	collectmoney.setUncollectMoney(feeBefore);
        	collectmoneyService.updateById(collectmoney);
        	return "SUCCESS";
    	}else if(type.equals("no")){
    		collectBasicInformation.setCollectState(KeyUtil.CHECK_STATE_FAIL_UNCHECKED);
        	collectBasicInformationService.updateById(collectBasicInformation);
        	return "SUCCESS";
    	}
    	return "FAIL";
    }
    /**
     * 获取收款登记列表,此权限用于查询所有已通过审核的功能
     */
    @RequestMapping(value = "/listbossquery")
    @ResponseBody
    public Object list(@RequestParam(required = false) String collectId , @RequestParam(required = false) String collectDate , @RequestParam(required = false) String collectTradePerson ,@RequestParam(required = false) String collectCarId,
    		@RequestParam(required = false) String collectCarNumber,@RequestParam(required = false) String collectCarDriver,@RequestParam(required = false) String collectRouteId,@RequestParam(required = false) String collectRouteStart,@RequestParam(required = false) String collectRouteEnd) {
    	Page<CollectBasicInformation> page = new PageFactory<CollectBasicInformation>().defaultPage();
    	List<CollectBasicInformation> result = collectBasicInformationService.getCollectBasic(page, collectId, collectDate, collectTradePerson, collectCarId, collectCarNumber, collectCarDriver, collectRouteId, collectRouteStart, collectRouteEnd);
    	page.setRecords(result);
    	return super.packForBT(page);
    }
    
    /**
     * 打开用于查看详情、打印、反审核的页面
     */
    @RequestMapping("/collectBasicInformation_updatequery/{collectBasicInformationId}")
    public String collectBasicInformationQuery(@PathVariable Integer collectBasicInformationId, Model model) {
    	ModelCollection modelCollection = new ModelCollection();
    	CollectBasicInformation collectBasicInformation = collectBasicInformationService.selectById(collectBasicInformationId);
    	
    	String collectId = collectBasicInformation.getCollectId();
    	EntityWrapper<CollectCarryInformation> entityWrapper1 = new EntityWrapper<>();
    	Wrapper<CollectCarryInformation> wrapper1 = entityWrapper1.eq("collect_collection_id", collectId);
    	List<CollectCarryInformation> collectCarryInformations = collectCarryInformationService.selectList(wrapper1);
    	
    	modelCollection.setCollectBasicInformation(collectBasicInformation);
    	modelCollection.setCollectCarryInformations(collectCarryInformations);
    	model.addAttribute("item", modelCollection);
        return "/query/collectBasicInformation/" + "collectBasicInformation_edit.html";
    }
    
    /**
     * 反审核操作
     */
    @RequestMapping(value = "/antiAudit")
    @ResponseBody
    public Object antiAudit(Integer id) {
    	CollectBasicInformation  collectBasicInformation = collectBasicInformationService.selectById(id);
    	//收款表数据还原
    		//减掉收款余额表中数据
    	Double fee = collectBasicInformation.getCollectThisMoney();
    		//根据收款信息找到对应的合同
    	EntityWrapper<CollectCarryInformation> entityWrapper = new EntityWrapper<>();
    	Wrapper<CollectCarryInformation> wrapper = entityWrapper.eq("collect_collection_id", collectBasicInformation.getCollectId());
    	CollectCarryInformation collectCarryInformation = collectCarryInformationService.selectList(wrapper).get(0);
    	String contractNumber = collectCarryInformation.getCollectContractNumber();
    		//获取收款表
    	EntityWrapper<Collectmoney> entityWrapper2 = new EntityWrapper<>();
    	Wrapper<Collectmoney> wrapper2 = entityWrapper2.eq("contract_number", contractNumber);
    	Collectmoney collectmoney = collectmoneyService.selectList(wrapper2).get(0);
    	Double feeBefore = collectmoney.getUncollectMoney()+fee;
    	collectmoney.setUncollectMoney(feeBefore);
    	collectmoneyService.updateById(collectmoney);
    	
    	//将数据置为未审核字段
    	collectBasicInformation.setCollectState(KeyUtil.CHECK_STATE_UNCHECKED);
    	//审核人员清空
    	collectBasicInformation.setCollectCheck(null);
    	collectBasicInformationService.updateById(collectBasicInformation);
    	return "SUCCESS";
    }
}
